package com.liliudong.rommath.plugin.storage.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.liliudong.rommath.plugin.storage.properties.StorageConfigProperties;
import com.liliudong.rommath.plugin.storage.service.StorageService;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.Date;

/**
 * 阿里OSS存储实现
 *
 * @author liliudong
 * @date 2025年01月04日 11:37
 */
@Service
@RequiredArgsConstructor
@ConditionalOnBean(OSS.class)
public class AliOssStorageServiceImpl implements StorageService {

    private final OSS ossClient;

    private final StorageConfigProperties storageConfigProperties;

    @Override
    public String putObject(String objectKey, InputStream inputStream) {
        ossClient.putObject(storageConfigProperties.getBucketName(), objectKey, inputStream);
        return objectKey;
    }

    @Override
    public String generatePresignedUrl(String objectKey, long expiration, DateField dateField) {
        DateTime date = DateUtil.offset(new Date(), dateField, (int) expiration);
        return ossClient.generatePresignedUrl(storageConfigProperties.getBucketName(), objectKey, date).toString();
    }

    @Override
    public String generatePresignedUrl(String objectKey) {
        return generatePresignedUrl(objectKey, 10, DateField.MINUTE);
    }

}
